package struts.form;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class Struts_xml {
	
	public Struts_xml(){
		
	}
	
	public static Map<String, XmlBean> struts_xml(String xmlPath)throws Exception{
		SAXBuilder builder = new SAXBuilder();
		Document document =  builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Map<String, XmlBean> actionMap = new HashMap<String, XmlBean>();
		Element actionmapping = root.getChild("action-mapping");
		List<Element> mappingList = actionmapping.getChildren();
		for (Element mapping : mappingList) {
			XmlBean xmlBean = new XmlBean();
			String name = mapping.getAttributeValue("name");
			xmlBean.setBeanName(name);
			Element formbeans = root.getChild("formbeans");
			List<Element> formList = formbeans.getChildren();
			for (Element form : formList) {
				if (form.getAttributeValue("name").equals(name)) {
					xmlBean.setFormClass(form.getAttributeValue("class"));
					break;
				}
			}
			String type = mapping.getAttributeValue("type");
			xmlBean.setActionClass(type);
			String path = mapping.getAttributeValue("path");
			xmlBean.setPath(path);
			List<Element> forwardList = mapping.getChildren();
			Map<String, String> map = new HashMap<String, String>();
			for (Element forward : forwardList) {
				String forName = forward.getAttributeValue("name");
				String forValue = forward.getAttributeValue("value");
				map.put(forName, forValue);
			}
			xmlBean.setActionForward(map);
			actionMap.put(path, xmlBean);
		}
		return actionMap;
	}

}
